layui.define(['form','laytpl'], function(exports) {
	var laytpl = layui.laytpl,
		$ = layui.jquery,
		form = layui.form,
		myDiagram=null;
	$(window).on('resize',function(){
		$('#myDiagram').height($(window).height()-130);
	}).trigger('resize');
	window.Fields =[
		{name:'name',title:'标识'},
		{name:'title',title:'标题'},
		{name:'realname',title:'客户姓名'},
		{name:'money',title:'贷款金额'},
	];
	var $go = go.GraphObject.make; // for conciseness in defining templates
	var Flow = {
		myDiagram : null,
		myContextMenu : null,
		options : {
			font : '14px "Helvetica Neue","PingFang SC","Hiragino Sans GB","Microsoft YaHei","微软雅黑",Arial,sans-serif',
			Colors : {
				start   : {fill:'#5FB878',stroke:'#E1E3E5',text:'#ffffff'},
				end     : {fill:'#DC3C00',stroke:'#E1E3E5',text:'#ffffff'},
				default : {fill:'#F7F9FE',stroke:'#E1E3E5',hover:'#E3F6FF',text:'#333333'},
				pointer : {fill:null,stroke:'#2991FF',text:null}
			}
		},
		showNodeAttr : function(obj){
			var data={
				text : {title:'节点名称',type:'text'},
				fzr : {title:'负责人',type:'textarea'},
				fields : {title:'字段权限',type:'fields'},
			};
			var vals = obj.data;
			for(var i in data){
				data[i]['value'] = vals[i] || '';
			}
			laytpl($('#AttrTpl').html()).render({id:vals.id,list:data}, function(html){
				$('#myInspectorDiv').html(html);
				form.render();
				$('.layui-tab-title li.nodetab').trigger('click');
			});

			console.info(data);
		},
		nodeDoubleClick : function (e, obj) {
			var clicked = obj.part;
			if (clicked !== null) {
				var thisemp = clicked.data;
				node_edit($("#wfuid").val(), thisemp.key, thisemp.text);
			}
		},
		nodeclick : function (e, obj) {
			var clicked = obj.part;
			if (clicked !== null) {
				var thisemp = clicked.data;
				Flow.showNodeAttr(obj.part);
			}
		},
		linkDoubleClick : function (e, obj) {
			var clicked = obj.part;
			if (clicked !== null) {
				var thisemp = clicked.data;
				console.log(thisemp);
				link_edit($("#wfuid").val(), thisemp.from, thisemp.to, thisemp.condition_type, thisemp.condition_value);
			}
		},
		initNode : function(){
			var showPorts = function (node, show) {
				var diagram = node.diagram;
				if (!diagram || diagram.isReadOnly || !diagram.allowLink) return;
				node.ports.each(function(port) {
					port.stroke = (show ? Flow.options.Colors.pointer.stroke : null);
				});
			}
			var nodeStyle = function () {
				return [
					{
						contextMenu: Flow.myContextMenu,
						locationSpot: go.Spot.Center,
						selectionAdornmentTemplate: $go(go.Adornment, "Vertical",
							$go(go.Panel, "Auto",
								$go(go.Shape, { fill: null, stroke: "#76BBEB", strokeWidth: 1 }),
								$go(go.Placeholder)
							)
						)
					},
					new go.Binding("location", "loc", go.Point.parse).makeTwoWay(go.Point.stringify), {
						locationSpot: go.Spot.Center,
						mouseEnter: function(e, obj) {
							showPorts(obj.part, true);
						},
						mouseLeave: function(e, obj) {
							showPorts(obj.part, false);
						}
					}
				];
			}
			var makePort = function (name, spot, output, input) {
				return $go(go.Shape, "Circle", {
					fill: "transparent",
					stroke: null,
					desiredSize: new go.Size(8, 8),
					alignment: spot,
					alignmentFocus: spot,
					portId: name,
					fromSpot: spot,
					toSpot: spot,
					fromLinkable: output,
					toLinkable: input,
					cursor: "pointer"
				});
			} 
			var TPL = function(name){
				Flow.myDiagram.nodeTemplateMap.add(name=='default' ? "" : name,
					$go(go.Node, "Spot", nodeStyle(),{
							doubleClick: Flow.nodeDoubleClick,
							click: Flow.nodeclick
						},
						$go(go.Panel, "Auto",
							$go(go.Shape, "RoundedRectangle", {
								minSize: new go.Size(150, 40),
								fill   : Flow.options.Colors[name].fill,
								stroke : Flow.options.Colors[name].stroke
							}),
							$go(go.TextBlock, name, {
									font: Flow.options.font,
									stroke: Flow.options.Colors[name].text
								},
								new go.Binding("text")
							)
						),
						makePort("L", go.Spot.Left, false, true),
						makePort("R", go.Spot.Right, false, true),
						name=='start' ? {} : makePort("T", go.Spot.Top, false, true),
						name=='end' ? {} : makePort("B", go.Spot.Bottom, true, false)
					)
				);
			}
			TPL("default");
			TPL("start");
			TPL("end");
			Flow.myDiagram.linkTemplate =$go(go.Link,
				{
					routing: go.Link.AvoidsNodes,
					curve: go.Link.JumpOver,
					corner: 5,
					toShortLength: 4,
					relinkableFrom: true,
					relinkableTo: true,
					reshapable: true,
					resegmentable: true,
					mouseEnter: function(e, link) {
						link.findObject("HIGHLIGHT").stroke = "rgba(30,144,255,0.2)";
					},
					mouseLeave: function(e, link) {
						link.findObject("HIGHLIGHT").stroke = "transparent";
					}
				}, 
				{
					doubleClick: Flow.linkDoubleClick
				},
				new go.Binding("points").makeTwoWay(),
				$go(go.Shape,{
					isPanelMain: true,
					strokeWidth: 8,
					stroke: "transparent",
					name: "HIGHLIGHT"
				}),
				$go(go.Shape,{
					isPanelMain: true,
					stroke: "#0db3a6",
					strokeWidth: 2
				}),
				$go(go.Shape,{
					toArrow: "SidewaysV",
					stroke: '#0db3a6',
					fill: "#0db3a6"
				}),
				$go(go.Panel, "Auto",{
						visible: false,
						name: "LABEL",
						segmentIndex: 2,
						segmentFraction: 0.5
					},
					new go.Binding("visible", "visible").makeTwoWay(),
					$go(go.Shape, "RoundedRectangle",{
						fill: "#F8F8F8",
						stroke: null
					}),
					$go(go.TextBlock, "Yes",{
							textAlign: "center",
							font: "10pt helvetica, arial, sans-serif",
							stroke: "#333333",
							editable: true
						},
						new go.Binding("text", "text").makeTwoWay()
					)
				)
			);
			Flow.myDiagram.toolManager.linkingTool.temporaryLink.routing = go.Link.Orthogonal;
			Flow.myDiagram.toolManager.relinkingTool.temporaryLink.routing = go.Link.Orthogonal;
		},
		initMenu : function(){
			var cxElement = document.getElementById("contextMenu");
			Flow.myContextMenu = $go(go.HTMLInfo, {
				show: showContextMenu,
				mainElement: cxElement
			});
			Flow.myDiagram.contextMenu = Flow.myContextMenu;
			cxElement.addEventListener("contextmenu", function(e) {
				e.preventDefault();
				return false;
			}, false);
			function showContextMenu(obj, diagram, tool) {
				var cmd = diagram.commandHandler;
				document.getElementById("cm_cut").style.display = cmd.canCutSelection() ? "block" : "none";
				document.getElementById("cm_copy").style.display = cmd.canCopySelection() ? "block" : "none";
				document.getElementById("cm_paste").style.display = cmd.canPasteSelection() ? "block" : "none";
				document.getElementById("cm_delete").style.display = cmd.canDeleteSelection() ? "block" : "none";
				cxElement.style.display = "block";
				var mousePt = diagram.lastInput.viewPoint;
				cxElement.style.left = mousePt.x+20 + "px";
				cxElement.style.top = 110+mousePt.y + "px";
			}
			window.cxcommand = function (event, val) {
				if (val === undefined) val = event.currentTarget.id;
				var diagram = Flow.myDiagram;
				switch (val) {
					case "cm_cut": diagram.commandHandler.cutSelection(); break;
					case "cm_copy": diagram.commandHandler.copySelection(); break;
					case "cm_paste": diagram.commandHandler.pasteSelection(diagram.lastInput.documentPoint); break;
					case "cm_delete": diagram.commandHandler.deleteSelection(); break;
					case "cm_color": {
						var color = window.getComputedStyle(document.elementFromPoint(event.clientX, event.clientY).parentElement)['background-color'];
							changeColor(diagram, color); break;
						}
				}
				diagram.currentTool.stopTool();
			}
		},
		init : function (data) {
			var showLinkLabel = function (e) {
				var label = e.subject.findObject("LABEL");
				if (label !== null) label.visible = (e.subject.fromNode.data.figure === "Diamond");
			}
			Flow.myDiagram =$go(go.Diagram, "myDiagram",{
				initialContentAlignment: go.Spot.TopCenter,
				allowDrop: true,
				"LinkDrawn": showLinkLabel,
				"LinkRelinked": showLinkLabel,
				"animationManager.duration": 800,
				"undoManager.isEnabled": true
			});
			var dg = Flow.myDiagram;
			//有改变时
			Flow.myDiagram.addDiagramListener("Modified", function(e) {
				var button = document.getElementById("SaveButton");
				if (button) button.disabled = !dg.isModified;
				var idx = document.title.indexOf("*");
				if (dg.isModified) {
					if (idx < 0) document.title += "*";
				} else {
					if (idx >= 0) document.title = document.title.substr(0, idx);
				}
			});
			Flow.initMenu();
			Flow.initNode();				
			// Show the primary selection's data, or blanks if no Part is selected:
			/*var inspector = new Inspector('myInspectorDiv', Flow.myDiagram,{
				// uncomment this line to only inspect the named properties below instead of all properties on each object:
				// includesOwnProperties: false,
				properties: {
					"节点名称": {title:'text'},
					"key": { readOnly: true, show: false},
					"颜色": { show: Inspector.showIfPresent, type: 'color' },
					"节点注释": { show: Inspector.showIfNode  },
					"连结注释": { show: Inspector.showIfLink },
					"isGroup": { readOnly: true, show: Inspector.showIfPresent },
					"choices": { show: false },  // must not be shown at all
					"password": { show: Inspector.showIfNode, type: 'password' }
				}
			});
			*/
			Flow.load(data);
			Flow.myOverview = $go(go.Overview, "myOverviewDiv",{observed:Flow. myDiagram, contentAlignment: go.Spot.Center });
			$('#BTN_SAVE').on('click',function(){
				var JsonData = Flow.myDiagram.model.toJson();
				vo['flows']['nodes'] = JsonData['linkDataArray'];
				vo['flows']['links'] = JsonData['linkDataArray'];
				Ajax.post(ADMIN_PATH +'/Build/save.html',{id:vo.id,flows:vo['flows']},function(d){
				},'JSON');
			})
			$('#BTN_VIEWJSON').on('click',function(){
				var JsonData = Flow.myDiagram.model.toJson();
				vo['flows']['nodes'] = JsonData['linkDataArray'];
				vo['flows']['links'] = JsonData['linkDataArray'];
				layer.open({
					area: ['670px', '510px'],
					title: 'JSON数据',
					content: '<div class="runtest"><textarea>'+JSON.stringify(vo['flows'],null,4)+'</textarea></div>'
				});
			})
		},		
		load : function(data) {
			jsondata = data;
			console.log(jsondata);
			Flow.myDiagram.model = new go.GraphLinksModel(jsondata["nodes"], jsondata["links"]);//go.Model.fromJson(document.getElementById("mySavedModel").value);
		}
	}
    exports('workflow', Flow);
})